﻿<?php
/**
* wechat php test
*/
require 'baidumap.php';
require "stock.php";

date_default_timezone_set('Asia/Hong_Kong');  //set time zone

define("TOKEN", "YouDaoEnglish");
$max_size = 500000;

$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        logger(" R ".$postStr);
        //extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            
            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "image":
                    $resultStr = $this->receiveImage($postObj);
                    break;
                case "location":
                    $resultStr = $this->receiveLocation($postObj);
                    break;
                default:
                    $resultStr = "unknow msg type";
                    break;
            }
            logger(" T ".$resultStr);
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    private function receiveText($object)
    {
        $funcFlag = 0;
        $keyword = trim($object->Content);

        $stockIndex = array(  
          '上证指数' => 'sh000001', 
          '深圳成指' => 'sz399001', 
          '沪深300'  => 'sh000300', 
          '中小板指' => 'sz399005', 
          '创业板指' => 'sz399006', 
          'Ｂ股指数' => 'sh000003',
          'B股指数'  => 'sh000003'
        ); 
        
        if($keyword == "?" || $keyword == "Hello2BizUser"){
            //$contentStr = "欢迎使用有道英语。本账号可为您提供翻译功能，支持中英文互译，支持字词句，且同时进行快速翻译和详细翻译。发送要查询的内容，可获得翻译结果。发送 ? 再加上您想要说的话，可以给我们留言！";
			$contentStr = "欢迎使用有道英语。本账号可为您提供翻译功能，支持中英文互译，支持字词句，且同时进行快速翻译和详细翻译。发送要查询的内容，可获得翻译结果。";
            $funcFlag = 0;
			$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        }
        else if (checkStockCode($keyword) != "nocode"){
            $contentStr = searchStock($keyword);
            $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        }
		// else if(substr($keyword,0,1) == "?" || substr($keyword,0,3) == "？" || substr($keyword,0,1) == " ")
		// {
			// $contentStr = "您的留言已经记录，我们看到后将尽快给您回复！";
			// $funcFlag = 1;
			// $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
		// }
        //else if(preg_match("/^\d+$/",$keyword) || preg_match("/^[A-Za-z]+$/",$keyword) ||preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$keyword)){
		// else if($keyword != "?")){
			// $contentStr = translate($keyword);
			// $resultStr = $this->transmitText($object, $contentStr);
        // }
        else {
            $contentStr = translate($keyword);
			$resultStr = $this->transmitText($object, $contentStr);
        }

        //Content 消息内容，大小限制在2048字节，字段为空为不合法请求
        //$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }
	
    private function receiveImage($object)
    {
        $contentStr = "receive a picture, url: ".$object->PicUrl;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
    
    private function receiveLocation($object)
    {
		$funcFlag = 0;
		$keyword = "医院";
		$radius = 2000;
		$oppentent = "亮视点";
		$TitleArray = array(); 
		$TitleArray[] = array(
        "title"=>"附近".($radius/1000)."公里内的".$keyword."店如下:不包括 ".$oppentent."", "description"=>"", "pic"=>"http://www.doucube.com/weixin/weather/icon/banner.jpg", "url" =>  "");
		//$searchArray = catchEntitiesFromLocationExceptOpponent($keyword, $object->Location_X, $object->Location_Y, $radius, $oppentent);
        $searchArray = catchEntitiesFromLocation($keyword, $object->Location_X, $object->Location_Y, $radius);
		$copyRight = copyRight(true);
        //$contentStr = "receive a location, 经度:".$object->Location_X." 纬度:".$object->Location_Y." 位置:".$object->Label;
        $resultStr = $this->transmitNews($object, array_merge_recursive($TitleArray, $searchArray, $copyRight), $funcFlag);
        return $resultStr;
    }
    
    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);

        return $resultStr;
    }

    private function transmitNews($object, $arr_item, $flag = 0)
    {
        //首条标题28字，其他标题39字
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        var_dump($arr_item);
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['title'], $item['description'], $item['pic'], $item['url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";

        $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $flag);
        return $resultStr;
    }
}

function logger($log_content)
{
    Global $max_size;
    $log_filename = date("Ymd").".xml";
    if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);sleep(1);}
    file_put_contents($log_filename, date('H:i:s').$log_content."\r\n", FILE_APPEND);
}

function customReply($keyword)
{
    if ((double)$keyword > 0 and (double)$keyword < 100){
        return "Message: ".$keyword;
    }else{
        return "Unknown: ".$keyword;
    }
}

function translate($keyword)
{
    $url = "http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".urlencode($keyword);
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	
	if(curl_errno($ch))
	{ echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);}
	
	curl_close($ch);

    //var_dump($content);
    $youdao = json_decode($output, true);
    $errorcode = $youdao['errorCode'];
	$translation = "快译: ".$youdao['translation'][0]."\n详解: "; //网络释义
    $phonetic = "发音: ".$youdao['basic']['phonetic']; //发音
    $explains = $youdao['basic']['explains']; //基本解释
    
    foreach ($explains as $value) {
        $translation = $translation."\n".$value;
    }
    $result = "";
    if(isset($errorcode)){
        switch ($errorcode){
            case 0:
                $result = $phonetic."\n".$translation;
				//$result = $translation;
                break;
            case 20:
                $result = "输入错误：要翻译的文本过长";
                break;
            case 30:
                $result = "系统错误：无法进行有效的翻译";
                break;
            case 40:
                $result = "输入错误：不支持的语言类型";
                break;
            case 50:
                $result = "系统错误：无效的密钥，没有权限翻译";
                break;
            default:
                $result = "系统错误：遇到未知错误，代码：".$errorcode;
                break;
        }
    }
    else{
        $result = "没有获得翻译结果？请发送?加内容与我们联系！";
    }
	//return $youdao['translation']['0'];
    return $result;
}

function copyRight($returnArray)
{
    $copyRightArray = array();
    //$copyRightArray[] = array("title"=>"天界神仙政府驻腾讯微信大使天气神", "description"=>"", "pic"=>"", "url" =>"");
    $copyRightArray[] = array("title"=>"方倍软件工作室 为您呈现", "description"=>"", "pic"=>"", "url" =>"");
    if($returnArray){
        return $copyRightArray;
    }else{
        return $copyRightArray[0]["title"];
    }
}

?>